package com.lu.barcode

import android.app.Activity
import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts

/**
 *author: luqihua
 *date:2023/4/10
 *description: 扫描辅助类  必须在Activity##onCreate之前创建

 **/
class BarcodeScanHelper(
    private val mContext: ComponentActivity,
    private val mScanListener: ScanListener
) {

    companion object {
        const val EXTRA_SCAN_RESULT = "scan_result"
        const val EXTRA_SCAN_ERROR = "scan_error"
        const val EXTRA_SCAN_BEEP = "extra_scan_beep"
    }

    private var mScanLauncher = mContext.registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
        val data = result.data
        if (data == null) {
            mScanListener.onFailure("the result data is null")
            return@registerForActivityResult
        }
        if (result.resultCode == Activity.RESULT_OK) {
            val resultText = data.getStringExtra(EXTRA_SCAN_RESULT)
            mScanListener.onSuccess(resultText)
        } else {
            val resultError = data.getStringExtra(EXTRA_SCAN_ERROR)
            mScanListener.onFailure(resultError)
        }
    }

    fun startScanning(beep: Boolean) {
        val intent = Intent(mContext, ScanningActivity::class.java).also {
            it.putExtra(EXTRA_SCAN_BEEP, beep)
        }
        mScanLauncher.launch(intent)
    }

}